package cn.iocoder.yudao.module.pay.framework.impl.alipay;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.api.pay.order.dto.UnifiedOrderCreateDTO;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayChannelEnum;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayDisplayModeEnum;
import cn.iocoder.yudao.module.api.pay.order.vo.UnifiedOrderVO;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;

/**
 * 支付宝【条码支付】的 PayClient 实现类
 * 文档：<a href="https://opendocs.alipay.com/open/194/105072">当面付</a>
 *
 * @author 芋道源码
 */
@Slf4j
public class AlipayBarPayClient extends AbstractAlipayPayClient {

    public AlipayBarPayClient(AlipayPayClientConfig config) {
        super(UnifiedPayChannelEnum.ALIPAY_BAR.getCode(), config);
    }

    @Override
    public UnifiedOrderVO doUnifiedOrder(UnifiedOrderCreateDTO dto) throws AlipayApiException {
        String authCode = MapUtil.getStr(dto.getChannelExtras(), "auth_code");
        if (StrUtil.isEmpty(authCode)) {
            throw exception0(BAD_REQUEST.getCode(), "条形码不能为空");
        }

        // 1.1 构建 AlipayTradePayModel 请求
        AlipayTradePayModel model = new AlipayTradePayModel();
        // ① 通用的参数
        model.setOutTradeNo(dto.getPayNo());
        model.setSubject(dto.getSubject());
        model.setBody(dto.getBody());
        model.setTotalAmount(formatAmount(dto.getPrice()));
        model.setScene("bar_code"); // 当面付条码支付场景
        // ② 个性化的参数
        model.setAuthCode(authCode);
        // ③ 支付宝条码支付只有一种展示
        String displayMode = UnifiedPayDisplayModeEnum.BAR_CODE.getCode();

        // 1.2 构建 AlipayTradePayRequest 请求
        AlipayTradePayRequest request = new AlipayTradePayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(dto.getNotifyUrl());
        request.setReturnUrl(dto.getRedirectUrl());

        // 2.1 执行请求
        AlipayTradePayResponse response;
        if (Objects.equals(channelConfig.getMode(), AlipayPayClientConfig.MODE_CERTIFICATE)) {
            // 证书模式
            response = client.certificateExecute(request);
        } else {
            response = client.execute(request);
        }
        // 2.2 处理结果
        if (!response.isSuccess()) {
            return buildClosedUnifiedOrderVO(dto, response);
        }
        if ("10000".equals(response.getCode())) { // 免密支付
            LocalDateTime successTime = LocalDateTimeUtil.of(response.getGmtPayment());
            UnifiedOrderVO respDTO = UnifiedOrderVO.successOf(response.getTradeNo(), response.getBuyerUserId(), successTime,
                    response.getOutTradeNo(), response);
            respDTO.setDisplayMode(displayMode);
            respDTO.setDisplayContent("");
            return respDTO;
        }
        // 大额支付，需要用户输入密码，所以返回 waiting。此时，前端一般会进行轮询
        return UnifiedOrderVO.waitingOf(displayMode, "",
                dto.getPayNo(), response.getTradeNo(), response);
    }

}
